package com.qf.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @Description: 公用常量
 * @Data: 2022/8/30 16:58
 * @Pacakge: com.qf.config
 * @ClassName: JdbcConfig
 * @Author: fan
 */
@PropertySource(value = "classpath:jdbc.properties")
//classpath:代表当前配置文件目录 resources
public class JdbcConfig {
    //expression包-->支持el表达式
    @Value("${driverClass}")
    private String driverClass;
    @Value("${jdbcUrl}")
    private String jdbcUrl;
    @Value("${user}")
    private String user;
    @Value("${password}")
    private String password;
    //将当前方法的返回值注入到IOC容器中
    @Scope("prototype")
    @Bean(name = "queryRunner")
    public QueryRunner getQueryRunner(){
        return new QueryRunner(getDataSource());
    }
    @Bean
    public DataSource getDataSource(){
        DataSource dataSource = new ComboPooledDataSource();
        try {
            //((ComboPooledDataSource)dataSource).setDriverClass("com.mysql.jdbc.Driver");
            ((ComboPooledDataSource)dataSource).setDriverClass(driverClass);
            //((ComboPooledDataSource)dataSource).setJdbcUrl("jdbc:mysql:///spring");
            ((ComboPooledDataSource)dataSource).setJdbcUrl(jdbcUrl);
            //((ComboPooledDataSource)dataSource).setUser("root");
            ((ComboPooledDataSource)dataSource).setUser(user);
            //((ComboPooledDataSource)dataSource).setPassword("f971014");
            ((ComboPooledDataSource)dataSource).setPassword(password);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return dataSource;

    }
}
